/*
 * 
 * 
 * 
 */
package com.hboxs.asl.controller.admin;

import com.hboxs.asl.FileInfo;
import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.Message;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.controller.app.PushController;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.ProductImage;
import com.hboxs.asl.entity.Question;
import com.hboxs.asl.entity.Sn;
import com.hboxs.asl.service.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * Controller - 提问问题
 */
@Controller("adminQuestionController")
@RequestMapping("/asl-admin/question")
public class QuestionController extends BaseController {

    @Resource(name = "questionServiceImpl")
    private QuestionService questionService;
    @Resource(name = "fileServiceImpl")
    private FileService fileService;
    @Resource(name = "productImageServiceImpl")
    private ProductImageService productImageService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "snServiceImpl")
    private SnService snService;

    /**
     * 添加
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap model, HttpSession session) {
        List<Member> members = memberService.findAll();
        model.addAttribute("members", members);
        session.setAttribute(IMAGE_TYPE , ProductImage.imageType.question);
        return "/admin/question/add";
    }

    /**
     * 获取对应的金额
     */
    @RequestMapping(value = "/opposite", method = RequestMethod.POST)
    public
    @ResponseBody
    Object opposite(Long type, Long teacherId) {
        Member teacher = memberService.find(teacherId);
        if (type == 1) {
            return JsonMessage.success(teacher.getMemberCertification().getPayFengshui());
        } else if (type == 2) {
            return JsonMessage.success(teacher.getMemberCertification().getPayGanqing());
        } else if (type == 3) {
            return JsonMessage.success(teacher.getMemberCertification().getPayShiye());
        } else if (type == 4) {
            return JsonMessage.success(teacher.getMemberCertification().getPayOther());
        } else {
            return JsonMessage.success(0);
        }
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Long memberId, Long teacherId, Question question, HttpServletRequest request, RedirectAttributes redirectAttributes , HttpSession session) {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 提问图片
        List<MultipartFile> questionImages = multipartRequest.getFiles("questionImage");
        for (Iterator<MultipartFile> iterator = questionImages.iterator(); iterator.hasNext(); ) {
            MultipartFile file = iterator.next();
            if (!fileService.isValid(FileInfo.FileType.image, file)) iterator.remove();
        }
        if (questionImages.size()!=0) {
            question.setImages(productImageService.buildForStringImages(questionImages, session.getAttribute(IMAGE_TYPE).toString()));
        }

        if (!isValid(question)) {
            return ERROR_VIEW;
        }
        Member teacher = memberService.find(teacherId);
        if(teacher != null) {
            question.setTeacher(teacher);
        }
        Member member = memberService.find(memberId);
        if(member != null) {
            question.setMember(member);
        }
        //设置状态为未回答
        question.setAnswerStatus(Question.AnswerStatus.no);
        //设置为已支付
        question.setPaymentStatus(Question.PaymentStatus.paid);
        //设置编号
        question.setSn(snService.generate(Sn.Type.payment));
        questionService.save(question);

        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.htm";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id, ModelMap model, HttpSession session) {
        session.setAttribute(IMAGE_TYPE , ProductImage.imageType.question);
        model.addAttribute("question", questionService.find(id));
        return "/admin/question/edit";
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Question question, RedirectAttributes redirectAttributes, HttpServletRequest request, HttpSession session) {

        if (!isValid(question)) {
            return ERROR_VIEW;
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 提问图片
        List<MultipartFile> questionImages = multipartRequest.getFiles("questionImage");
        for (Iterator<MultipartFile> iterator = questionImages.iterator(); iterator.hasNext(); ) {
            MultipartFile file = iterator.next();
            if (!fileService.isValid(FileInfo.FileType.image, file)) iterator.remove();
        }
        if (questionImages.size()!=0) {
            question.getImages().addAll(productImageService.buildForStringImages(questionImages, session.getAttribute(IMAGE_TYPE).toString()));
        }

        questionService.update(question, "member", "teacher", "answerStatus", "answerContent", "sn");
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);

        return "redirect:list.htm";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Pageable pageable, ModelMap model) {
        model.addAttribute("page", questionService.findPage(pageable));
        return "/admin/question/list";
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public
    @ResponseBody
    Message delete(Long[] ids) {
        questionService.delete(ids);
        return SUCCESS_MESSAGE;
    }


    /**
     * 申请退款
     * @param id
     * @return
     */
    @RequestMapping(value = "/apply_refund", method = RequestMethod.GET)
    public String applyRefund(Long id) {
        Question question = questionService.find(id);
        question.setPaymentStatus(Question.PaymentStatus.refundSuccess);
        questionService.update(question);
        //处理用户退款
        Member member = question.getMember();
        member.setBalance(member.getBalance().add(question.getPayPrice()));
        memberService.update(member);
        //个推提示
        PushController.notice(member, "您的退款已返回到余额");
        return "redirect:list.htm";
    }

}
